<?php
/**
 * Copyright (c) 2008 Derdubor A/S
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

if (!defined('KEEPITCLOSE_ROOT'))
{
    // seems like autoPrepend is borked, so we try to rescue ourselves
    require_once '../include/autoPrepend.php';
}

if (empty($_GET['url']))
{
    exit("No URL provided.");
}

$url = $_GET['url'];

// default time to live
$ttl = 3600;

// time to live in cache service
if (isset($config['ttl']))
{
    $ttl = (int) $config['ttl'];
}

if (isset($_GET['ttl']))
{
    $ttl = (int) $_GET['ttl'];
}

// support "update every x seconds since midnight (time() dividable by ttlWindowSize)"
if (!empty($_GET['ttlWindowSize']))
{
    $sequence = max(1, (int) $_GET['ttlWindowSize']);
    $offset = 0;
    
    if (!empty($_GET['ttlWindowOffset']))
    {
        $offset = max(0, (int) $_GET['ttlWindowOffset']);
    }
    
    if ($sequence > 0)
    {
        $ttl = $sequence - (time() % $sequence);
    }

    unset($sequence);
}

$saver = new Keepitclose_Saver($storage);
$saver->setTTL($ttl);

$data = $saver->get($url);

if($data)
{
    foreach($data['headers'] as $header)
    {
        header($header['key'] . ': ' . $header['value']);
    }
    
    print($data['content']);
}


